package logic

import (
	"context"
	"errors"
	"houseRpc/cache"
	"houseRpc/models"

	"houseRpc/house"
	"houseRpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *house.LoginRequest) (*house.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var u models.User
	var err error

	u.Mobile = in.Mobile
	if err = u.GetUserByMobile(); err != nil {
		logx.Error("用户信息获取失败")
		return nil, errors.New("用户信息获取失败")
	}
	if u.ID == 0 {
		logx.Error("当前用户不存在")
		return nil, errors.New("当前用户不存在")
	}

	sms, err := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	if err != nil {
		return nil, err
	}

	if sms == "" {
		logx.Error("验证码失效")
		return nil, errors.New("验证码失效")
	}

	if sms != in.SmsCode {
		logx.Error("短信验证码错误")
		return nil, errors.New("短信验证码错误")
	}
	return &house.LoginResponse{
		Id: int64(u.ID),
	}, nil
}
